<template>
  <BenchCompWrapper title="入库时间分析">
    <template v-slot:btn>
      <px-tooltip content="跳转备件台账" placement="top">
        <px-button class="button" text type="primary" @click="goLedger">
          <px-icon><ArrowRight /></px-icon>
        </px-button>
      </px-tooltip>
    </template>
    <template v-slot:content>
      <div v-show="!empty" ref="chartContainer" :style="{ width: '100%', height: '300px' }" />
      <px-empty v-if="empty" description="暂无数据" />
    </template>
  </BenchCompWrapper>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import { useRouter } from "vue-router";
import { ref, computed, onMounted, type Ref } from "vue";

import { useEchartsResize } from "@/hooks/useEchartsResize";
import { getDataOfInDateAnalysis } from "@/api/erc/spareParts/signboard";
import type { ResponseDataOfInDateAnalysis, ResponseDataOfInDateAnalysisItem } from "@/api/erc/spareParts/signboard";

import BenchCompWrapper from "./BenchCompWrapper.vue";

const options: echarts.EChartsOption = {
  tooltip: {
    trigger: "item"
  },
  legend: {
    top: "5%",
    left: "center"
  },
  series: [
    {
      name: "",
      type: "pie",
      startAngle: 0,
      endAngle: 360,
      itemStyle: {
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 2
      },
      radius: ["40%", "70%"],
      center: ["50%", "60%"],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      },
      color: ["#4786FF  ", "#14C7C7 ", "#FFB266 ", "#8B8AE6 "]
    }
  ]
};

const router = useRouter();

const empty = ref(false);
const data = ref<ResponseDataOfInDateAnalysis>([]);
const chartContainer: Ref<HTMLElement | null> = ref(null);
const chartInstance: Ref<echarts.ECharts | null> = ref(null);

const echartsData = computed(() => {
  return data.value.map((item: ResponseDataOfInDateAnalysisItem) => ({
    name: item.name,
    value: item.value
  }));
});

useEchartsResize(chartInstance, chartContainer, options);

const isEmpty = () => {
  let flag = true;
  if (echartsData.value?.length) {
    echartsData.value.forEach(item => {
      if (item.value > 0) {
        flag = false;
      }
    });
  }

  return flag;
};

const renderChart = (): void => {
  if (!isEmpty()) {
    empty.value = false;
    if (chartInstance.value?.setOption) {
      chartInstance.value.setOption({
        series: [
          {
            data: echartsData.value
          }
        ]
      });
    }
  } else {
    empty.value = true;
  }
};

const goLedger = () => {
  router.push("/erc/spareParts/ledger");
};

//入库时间分析
const getChartData = async params => {
  try {
    const res = await getDataOfInDateAnalysis(params);
    data.value = res;
    renderChart();
  } catch (error) {
    console.log("service error", error);
  }
};

defineExpose({
  getChartData
});

onMounted(() => {
  renderChart();
});
</script>
